package com.ljkj.cordial.chat.plugins.receiver;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;

import com.nic.view.util.JToast;

/**
 * @description:
 * @author: Panwei
 * @date: 2020/3/19 9:31
 */
public class HeadsetPlugReceiver extends BroadcastReceiver {

    private static boolean isHeadset = false;
    private static boolean isBluetoothHeadset = false;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
            if (intent.hasExtra("state")) {
                if (intent.getIntExtra("state", 0) == 0) {
                    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                    if (BluetoothProfile.STATE_CONNECTED == adapter.getProfileConnectionState(BluetoothProfile.HEADSET)) {
                        isHeadset = true;
                        isBluetoothHeadset = true;
                        return;
                    }
                    isHeadset = false;
                } else if (intent.getIntExtra("state", 0) == 1) {
                    isHeadset = true;
                }
            }
        } else if (BluetoothHeadset.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
            BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
                int state = adapter.getProfileConnectionState(BluetoothProfile.HEADSET);
                if (BluetoothProfile.STATE_CONNECTED == state) {
                    isHeadset = true;
                    isBluetoothHeadset = true;
                } else if (BluetoothProfile.STATE_DISCONNECTED == state) {
                    isHeadset = false;
                    isBluetoothHeadset = false;
                }
            }
        }
    }

    public static boolean isHeadset() {
        return isHeadset;
    }

    public static boolean isIsBluetoothHeadset() {
        return isBluetoothHeadset;
    }
}
